import React, { createContext, useContext, useReducer, ReactNode } from 'react';
import { 
  UnifiedAnalysisResult, 
  EditorMarker,
  AnalysisConfig 
} from '../types/analysis';

// 分析状态接口
export interface AnalysisState {
  // SQL内容和配置
  sqlContent: string;
  sourceDbType: string;
  targetDbType: string;
  aiEnhancementEnabled: boolean;
  userId: number;

  // 分析结果
  analysisResult: UnifiedAnalysisResult | null;
  editorMarkers: EditorMarker[];
  isAnalyzing: boolean;
  lastAnalysisTime: number | null;

  // 编辑器状态
  cursorPosition: { line: number; column: number };
  
  // 配置
  analysisConfig: AnalysisConfig;

  // UI状态
  selectedIssueId: string | null;
  activeTab: string;
}

// 动作类型
export type AnalysisAction =
  | { type: 'SET_SQL_CONTENT'; payload: string }
  | { type: 'SET_SOURCE_DB_TYPE'; payload: string }
  | { type: 'SET_TARGET_DB_TYPE'; payload: string }
  | { type: 'SET_AI_ENHANCEMENT'; payload: boolean }
  | { type: 'SET_USER_ID'; payload: number }
  | { type: 'SET_ANALYSIS_RESULT'; payload: UnifiedAnalysisResult | null }
  | { type: 'SET_EDITOR_MARKERS'; payload: EditorMarker[] }
  | { type: 'SET_IS_ANALYZING'; payload: boolean }
  | { type: 'SET_CURSOR_POSITION'; payload: { line: number; column: number } }
  | { type: 'SET_ANALYSIS_CONFIG'; payload: Partial<AnalysisConfig> }
  | { type: 'SET_SELECTED_ISSUE_ID'; payload: string | null }
  | { type: 'SET_ACTIVE_TAB'; payload: string }
  | { type: 'CLEAR_ANALYSIS_RESULT' }
  | { type: 'RESET_STATE' };

// 初始状态
const initialState: AnalysisState = {
  sqlContent: '',
  sourceDbType: 'ORACLE',
  targetDbType: 'GOLDENDB',
  aiEnhancementEnabled: false,
  userId: 1,

  analysisResult: null,
  editorMarkers: [],
  isAnalyzing: false,
  lastAnalysisTime: null,

  cursorPosition: { line: 1, column: 1 },

  analysisConfig: {
    enableRealTimeAnalysis: false,
    enableAutoOptimization: false,
    debounceDelay: 1000,
    maxResults: 100,
    showLineNumbers: true,
    highlightIssues: true,
  },

  selectedIssueId: null,
  activeTab: 'issues',
};

// Reducer函数
function analysisReducer(state: AnalysisState, action: AnalysisAction): AnalysisState {
  switch (action.type) {
    case 'SET_SQL_CONTENT':
      return { ...state, sqlContent: action.payload };
    
    case 'SET_SOURCE_DB_TYPE':
      return { ...state, sourceDbType: action.payload };
    
    case 'SET_TARGET_DB_TYPE':
      return { ...state, targetDbType: action.payload };
    
    case 'SET_AI_ENHANCEMENT':
      return { ...state, aiEnhancementEnabled: action.payload };
    
    case 'SET_USER_ID':
      return { ...state, userId: action.payload };
    
    case 'SET_ANALYSIS_RESULT':
      return { 
        ...state, 
        analysisResult: action.payload,
        lastAnalysisTime: action.payload ? Date.now() : null
      };
    
    case 'SET_EDITOR_MARKERS':
      return { ...state, editorMarkers: action.payload };
    
    case 'SET_IS_ANALYZING':
      return { ...state, isAnalyzing: action.payload };
    
    case 'SET_CURSOR_POSITION':
      return { ...state, cursorPosition: action.payload };
    
    case 'SET_ANALYSIS_CONFIG':
      return { 
        ...state, 
        analysisConfig: { ...state.analysisConfig, ...action.payload } 
      };
    
    case 'SET_SELECTED_ISSUE_ID':
      return { ...state, selectedIssueId: action.payload };
    
    case 'SET_ACTIVE_TAB':
      return { ...state, activeTab: action.payload };
    
    case 'CLEAR_ANALYSIS_RESULT':
      return { 
        ...state, 
        analysisResult: null, 
        editorMarkers: [], 
        selectedIssueId: null,
        lastAnalysisTime: null
      };
    
    case 'RESET_STATE':
      return { ...initialState, analysisConfig: state.analysisConfig };
    
    default:
      return state;
  }
}

// Context创建
const AnalysisContext = createContext<{
  state: AnalysisState;
  dispatch: React.Dispatch<AnalysisAction>;
} | null>(null);

// Provider组件
export function AnalysisProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(analysisReducer, initialState);

  return (
    <AnalysisContext.Provider value={{ state, dispatch }}>
      {children}
    </AnalysisContext.Provider>
  );
}

// 自定义Hook
export function useAnalysisContext() {
  const context = useContext(AnalysisContext);
  if (!context) {
    throw new Error('useAnalysisContext must be used within an AnalysisProvider');
  }
  return context;
}

// 便捷的操作函数
export function useAnalysisActions() {
  const { dispatch } = useAnalysisContext();

  return {
    setSqlContent: (content: string) => 
      dispatch({ type: 'SET_SQL_CONTENT', payload: content }),
    
    setSourceDbType: (dbType: string) => 
      dispatch({ type: 'SET_SOURCE_DB_TYPE', payload: dbType }),
    
    setTargetDbType: (dbType: string) => 
      dispatch({ type: 'SET_TARGET_DB_TYPE', payload: dbType }),
    
    setAiEnhancement: (enabled: boolean) => 
      dispatch({ type: 'SET_AI_ENHANCEMENT', payload: enabled }),
    
    setAnalysisResult: (result: UnifiedAnalysisResult | null) => 
      dispatch({ type: 'SET_ANALYSIS_RESULT', payload: result }),
    
    setEditorMarkers: (markers: EditorMarker[]) => 
      dispatch({ type: 'SET_EDITOR_MARKERS', payload: markers }),
    
    setIsAnalyzing: (isAnalyzing: boolean) => 
      dispatch({ type: 'SET_IS_ANALYZING', payload: isAnalyzing }),
    
    setCursorPosition: (position: { line: number; column: number }) => 
      dispatch({ type: 'SET_CURSOR_POSITION', payload: position }),
    
    updateAnalysisConfig: (config: Partial<AnalysisConfig>) => 
      dispatch({ type: 'SET_ANALYSIS_CONFIG', payload: config }),
    
    setSelectedIssueId: (id: string | null) => 
      dispatch({ type: 'SET_SELECTED_ISSUE_ID', payload: id }),
    
    setActiveTab: (tab: string) => 
      dispatch({ type: 'SET_ACTIVE_TAB', payload: tab }),
    
    clearAnalysisResult: () => 
      dispatch({ type: 'CLEAR_ANALYSIS_RESULT' }),
    
    resetState: () => 
      dispatch({ type: 'RESET_STATE' }),
  };
}